package com.industrial.premu.util;

import org.springframework.stereotype.Component;

import javax.validation.*;
import java.util.List;
import java.util.Set;

@Component
public class ValidationUtil {

    public static <T>  void validate(T t) throws ValidationException {
        ValidatorFactory vFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = vFactory.getValidator();
        Set<ConstraintViolation<T>> set =  validator.validate(t);
        if(set.size()>0){
            StringBuilder validateError = new StringBuilder();
            for(ConstraintViolation<T> val : set){
                validateError.append(val.getMessage());
            }
            throw new ValidationException(validateError.toString());
        }

    }

    public static <T>  void validate(List<T> list) throws ValidationException {
        ValidatorFactory vFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = vFactory.getValidator();
        for(T t : list) {
            Set<ConstraintViolation<T>> set =  validator.validate(t);
            if(set.size()>0){
                StringBuilder validateError = new StringBuilder();
                for(ConstraintViolation<T> val : set){
                    validateError.append(val.getInvalidValue()+val.getMessage());
                }
                throw new ValidationException(validateError.toString());
            }
        }

    }
}
